package com.tanhua.dubbo.api.impl.mongo;/*
 *FileName:  VoiceApiImpl
 * Author:   ASUS
 * Date  :   2021/5/21 14:22
 * */

import com.tanhua.domain.mongo.Voice;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


import java.util.List;

@Service(timeout = 200000)
public class VoiceApiImpl implements VoiceApi {

    //一般写进mongo的  都用mongotemplate  写进mysql的 用mapper
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    /**
     * 发语音  保存语音到数据库
     *
     * @param voice
     */
    @Override
    public void saveSound(Voice voice) {
        voice.setVid(idService.getNextId("video"));
        mongoTemplate.save(voice);
    }

    /**
     * 接收语音  获取语音
     *
     * @return
     */
    @Override
    public Voice getVoice(Long userId) {
        Query query = new Query(
                Criteria.where("userId").ne(userId)//排除自己的语音
        );
        query.with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.findOne(query, Voice.class);
    }

    /**
     * 根据语音的id来删除数据
     *
     * @param id
     */
    @Override
    public void delete(ObjectId id) {
        Query query = new Query(
                Criteria.where("_id").is(new ObjectId(String.valueOf(id)))
        );
        mongoTemplate.remove( query, Voice.class);
    }

}
